import datetime;
import json
RECORDS_FILE='records.json';
def validate_date(date_str):
    try:
        datetime.datetime.strptime(date_str,'%Y-%m-%d');
        return True;
    except ValueError:
        return False;
def query_records(records):
    query_type= input("请输入查询类型（1.日期/2.日期范围/3.类别）：");
    if query_type=="1":
        date=input("请输入查询日期(YYYY-MM-DD)：");
        while not validate_date(date):
            print("日期格式错误，请重新输入(YYYY-MM-DD)：");
            date=input();
        def match_date(record):
            return record['date']==date;
        print("\n---查询结果---");
        display_records_by_condition(match_date,"收入",records["incomes"]);
        display_records_by_condition(match_date,"支出",records["expenses"]);
    elif query_type=="2":
        start_date=input("请输入开始日期(YYY-MM-DD)：");
        end_date=input("请输入结束日期(YYY-MM-DD)：");
        while not validate_date(start_date) or not validate_date(end_date):
            print("日期格式错误，请重新输入(YYY-MM-DD)：");
            start_date=input("请输入开始日期(YYY-MM-DD)：");
            end_date=input("请输入结束日期(YYY-MM-DD)：");
        start_date=datetime.datetime.strptime(start_date,'%Y-%m-%d').date();
        end_date=datetime.datetime.strptime(end_date,'%Y-%m-%d').date();
        def match_date_range(record):
            return start_date<=datetime.datetime.striptime(record['date'],'%Y-%m-%d').date()<=end_date;
        print("\n---查询结果---")
        display_records_by_condition(match_date_range,"收入",records["incomes"]);
        display_records_by_condition(match_date_range,"支出",records["expenses"]);
    elif query_type=="3":
        category=input("请输入查询类别：");
        def match_category(record):
            return record['category']==category
        print("\n---查询结果---");
        display_records_by_condition(match_category,"收入",records["incomes"]);
        display_records_by_condition(match_category,"支出",records["expenses"]);
def display_records_by_condition(condition,record_type,records):
    matched_records=[record for record in records if condition(record)];
    if not matched_records:
        print(f"没有找到{record_type}记录。");
    else:
        print(f"\n---{record_type}记录 ---");
        for record in matched_records:
            print(f"日期:{record['date']}, 金额:{record['amount']}, 类别:{record['category']}, 备注:{record['note']}");
def load_records():
    try:
        with open(RECORDS_FILE,'r') as file:
            return json.load(file)
    except FileNotFoundError:
        return{"incomes":[],"expenses":[]};
def save_records(records):
    with open(RECORDS_FILE,'w') as file:
        json.dump(records,file,indent=4);
def add_income(amount,category,note,date,records):
    if amount<=0:
        print("金额必须为正数！")
        return
    records["incomes"].append({
        "date":date,"amount":amount,"category":category,"note":note});
    save_records(records);
    print("收入已成功记录！");
    input("按enter键返回主菜单");
    return main();
def add_expense(amount,category,note,date,records):
    if amount <=0:
        print("金额必须为正数！");
        return
    records["expenses"].append({
        "date":date,"amount":amount,"category":category,"note":note});
    save_records(records);
    print("支出已成功记录!");
    input("按enter键返回主菜单");
    return main();
def display_records(records):
    print("收入记录：");
    for record in records["incomes"]:
        print(record);
    print("\n支出记录：");
    for record in records["expenses"]:
        print(record);
def main():
    records=load_records();
    while True:
        print("==============================\n    欢迎使用个人账单管理系统\n==============================");
        print("请选择操作：\n1.记录收入\n2.记录支出\n3.查看所有账单\n4.查询账单\n5.退出系统");
        choice=input("请输入选项序号：");
        if choice=='1':
            print("==============================\n    欢迎使用个人账单管理系统\n==============================");
            print("请输入收入信息:");
            date=input("日期（YYYY-MM-DD）:");
            while not validate_date(date):
                print("日期格式错误，请重新输入（YYY-MM-DD）：");
                date=input();
            amount=float(input("金额:"));
            category=input("类别（如工资、奖金等):");
            note=input("备注:");
            add_income(amount,category,note,date,records);
        elif choice=='2':
            print("==============================\n    欢迎使用个人账单管理系统\n==============================");
            print("请输入支出信息:");
            date=input("日期（YYYY-MM-DD）：");
            while not validate_date(date):
                print("日期格式错误，请重新输入（YYY-MM-DD）：");
                date=input();
            amount=float(input("金额:"));
            category=input("类别（如工资、奖金等）:");
            note=input("备注:");
            add_expense(amount,category,note,date,records);
        elif choice=='3':
            print("==============================\n    欢迎使用个人账单管理系统\n==============================");
            print("以下是金额记录：");
            display_records(records);
        elif choice=='4':
            print("==============================\n    欢迎使用个人账单管理系统\n==============================");
            query_records(records);
        elif choice=='5':
            print("==============================\n    欢迎使用个人账单管理系统\n==============================");
            print("退出系统，再见！");
            break;
        else:
            print("无效选择，请重新选择。");
if __name__=="__main__":
     main();

